﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GameSchoolApplication.Models;

namespace GameSchoolApplication.Repositories
{
    public class StoreItemRepository
    {
        gsDBDataContext link = new gsDBDataContext();

        /// <summary>
        /// Getting a storeItem
        /// Precondition:
        /// Postcondition: A store item is returned
        /// Author: Arona/Bjarmi mod. by Alma
        /// Date: 7.5. 2012
        /// </summary>
        public StoreItem getStoreItemByID(int storeItemID)
        {
            StoreItem selectedItem = (from s in link.StoreItems
                               where s.itemID == storeItemID
                               select s).First();            
            return selectedItem; 
        }

        /// <summary>
        /// /// Returns a list of all store items
        /// Precondition:
        /// Postcondition: Itemlist has been returned
        /// Author: Aron/Bjarmi mod. by Alma
        /// Date: 07.05.2012

        /// </summary>
        public IQueryable<StoreItem> getAllItems()
        {
            return link.StoreItems;
        }

        /// <summary>
        /// Adds an item to the database.
        /// Precondition: 
        /// Postcondition: Item has been added to the database
        /// Author: Aron/Bjarmi mod. by Alma
        /// Date: 07.05.2012
        /// </summary>
        public bool addItem(StoreItem item)
        {
            try
            {
                link.StoreItems.InsertOnSubmit(item);
            }
            catch (Exception)
            {
                return false;
            }
            return true; 
        }

        /// <summary>
        /// Editing the store items
        /// Precondition: User must be an administrator and the item must exist
        /// Postcondition: Item information has been updated in the database
        /// Author: Aron Mar mod. by Alma
        /// Date: 7.5. 2012
        /// </summary>
        public bool editItem(StoreItem item)
        {
            try
            {
                var it = (from i in link.StoreItems
                            where i.itemID == item.itemID
                            select i).First();

                it.itemName = item.itemName;
                it.descript = item.descript;
                it.sbuxPrice = item.sbuxPrice;

                save();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
            
        }

        /// <summary>
        /// Saves changes to database
        /// Precondition:
        /// Postcondition: Database has been updated
        /// Author: Aron og Bjarmi
        /// Date: 03.05.2012
        /// </summary>
        public void save()
        {
            link.SubmitChanges();
        }

    }
}